package com.meihua.baoleyi.dialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.pay.WxPay;
import com.meihua.baoleyi.utils.IsPayPasswordUtil;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.view.PayWayView;
import com.meihua.baoleyi.widget.AlertDialog;
import com.meihua.baoleyi.widget.CustomerKeyboard;
import com.meihua.baoleyi.widget.PasswordEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：jzm on 2017/11/2.
 * 支付弹窗
 */

public class PayDialog extends DialogFragment implements CustomerKeyboard.CustomerKeyboardClickListener, PasswordEditText.PasswordFullListener {

    private static final String ACTION_NAME = "PayDialog";

    private TextView open;
    private PayWayView mPayWayView;
    private ImageView back;
    private int money; //当前导购对应的金额
    private int levelId; //购买会员等级的id
    private int payWay = 1; //支付方式
    private AlertDialog dialog;
    private PasswordEditText passwordEditText;
    private CustomerKeyboard mCustomerKeyboard;
    private String payPassword;
    private Intent mIntent;

    public PayDialog() {
        super();
    }

    public static PayDialog getInstance(int money, int levelId){
        PayDialog mPayDialog = new PayDialog();
        Bundle mBundle = new Bundle();
        mBundle.putInt("money", money);
        mBundle.putInt("levelId", levelId);
        mPayDialog.setArguments(mBundle);
        return mPayDialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //需要去掉标题
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置dialogd的进出动画
//        getDialog().getWindow().setWindowAnimations(R.style.animate_dialog);
        View view = inflater.inflate(R.layout.dialog_pay, container, false);
        initView(view);
        return view;
    }

    /**
     * 初始化数据
     * @param view
     */
    private void initView(View view) {
        open = view.findViewById(R.id.tv_open);
        back = view.findViewById(R.id.iv_back);
        mPayWayView = view.findViewById(R.id.pay_view);

        money = getArguments().getInt("money", 0);
        levelId = getArguments().getInt("levelId", 0);
        open.setText("确认支付¥"+money);
        mIntent = new Intent(ACTION_NAME);
        mIntent.putExtra("levelId", levelId);
        setLinstener();
        getServerData();
    }

    /**
     * 设置点击监听
     */
    private void setLinstener() {
        //返回
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        //立即开通
        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay();
            }
        });
        //支付方式选择回调
        mPayWayView.setOnPaycheckInterface(new PayWayView.OnPaycheckInterface() {
            @Override
            public void onPayCheck(int way) {
                payWay = way;
            }
        });
    }

    /**
     * 点击支付
     */
    private void pay() {
        switch (payWay) {
            case 1: //微信
                getPayData(1);
                break;
            case 2: //余额
                //判断是否设置了支付密码
                IsPayPasswordUtil.isPayPassword(getActivity(), new IsPayPasswordUtil.OnIsPayPassword() {
                    @Override
                    public void isSetPayPassword(boolean isSet) {
                        if (isSet) {
                            showPasswordDialog();
                        }
                    }
                });
                break;
            case 3: //银行卡
                ToastUtil.show(getActivity(), "银行卡服务尚未开通!请选择其他方式");
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Window mWindow = getDialog().getWindow();
        //设置背景颜色，只有设置了这个属性，宽度才能全屏MANTC_PARENT
        mWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        WindowManager.LayoutParams mParams = mWindow.getAttributes();
        mParams.gravity = Gravity.BOTTOM;
        mParams.width = getActivity().getResources().getDisplayMetrics().widthPixels;
        mParams.height = (int)(getActivity().getResources().getDisplayMetrics().heightPixels*0.5);
        mWindow.setAttributes(mParams);
        //设置点击外面不能消失
        getDialog().setCanceledOnTouchOutside(false);
    }

    /**
     * 获取展示数据
     */
    public void getServerData() {

    }

    /**
     * 获取支付数据
     * @return
     */
    public void getPayData(final int payWay) {
        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        String user_id = MyApp.getInstance().getUser_id();
        treeMap.put("user_id", user_id);
        treeMap.put("level_id", levelId+"");
        treeMap.put("status", payWay+"");
        if (payWay == 2) { //余额支付才有支付密码
            treeMap.put("pay_password", payPassword);
        }
        NetHelper.post(APIServer.MEMBER_RECHARGE, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                JSONObject json;
                try {
                    json = new JSONObject(s);
                    if (payWay == 1) { //微信
                        WxPay.wxPay(getActivity(), s);
                        dismiss();
                    }
                    if (payWay == 2) { //余额
                        payBalance(s);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }

            }
        });
        //余额支付成功干掉密码框
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
    }

    /**
     * 余额支付
     * @param s
     */
    private void payBalance(String s) {
        try {
            JSONObject json = new JSONObject(s);
            String code = json.getString("code");
            if (code.equals("200")) {
                ToastUtil.show(getActivity(), json.getString("msg"));
                getContext().sendBroadcast(mIntent);
                dismiss();
            } else {
                ToastUtil.show(getActivity(), json.getString("msg"));
            }
        } catch (JSONException e) {}
    }

    /**
     * 弹出输入密码对话框
     */
    private void showPasswordDialog() {
        if (dialog != null) {
            return;
        }
        //弹出dialog输入框
        dialog = new AlertDialog.Builder(getActivity()).
                setContentView(R.layout.activity_password).
                fullWith().
                setCancelable(true).
                formBottom(true).
                show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog1) {
                dialog = null;
            }
        });
        passwordEditText = dialog.getView(R.id.password);
        mCustomerKeyboard = dialog.getView(R.id.customer_keyboard);
        mCustomerKeyboard.setOnCustomerKeyboardClickListener(this);
        passwordEditText.setEnabled(false);
        passwordEditText.setOnPasswordFullListener(this);
    }

    @Override
    public void click(String numder) {
        passwordEditText.addPassword(numder);
    }

    @Override
    public void delete() {
        passwordEditText.deleteLastPassword();
    }

    @Override
    public void passwordFull(final String password) {
        payPassword = password;
        getPayData(2);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
